package com.zeroone.star.sample.controller;

import cn.hutool.core.date.DateTime;
import com.zeroone.star.project.components.fastdfs.FastDfsClientComponent;
import com.zeroone.star.project.components.fastdfs.FastDfsFileInfo;
import com.zeroone.star.project.vo.JsonVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 演示FastDFS使用
 */

@Controller
@RequestMapping("file")
@Api(tags = "文件上传下载演示")
public class FileController{
    @Resource
    FastDfsClientComponent dfsClient;

    @Value("${fastdfs.nginx-servers}")
    private String fileServerUrl;

    @SneakyThrows
    @ApiOperation("上传文件")
    @PostMapping("upload")
    @ResponseBody
    public JsonVO<String> upload(MultipartFile file){
        //获取上传文件的后缀名称
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);

        //上传文件
        FastDfsFileInfo fastDfsFileInfo = dfsClient.uploadFile(file.getBytes(), suffix);
        if (fastDfsFileInfo != null){
            return JsonVO.success(dfsClient.fetchUrl(fastDfsFileInfo,fileServerUrl,true));
        }
        return JsonVO.fail("上传失败");
    }

    @SneakyThrows
    @ApiOperation("下载文件")
    @GetMapping(value = "download",produces = "image/jpeg")
    public ResponseEntity<byte[]> download(String group,String storageId){
        //从文件服务器下载文件
        byte[] bytes = dfsClient.downloadFile(FastDfsFileInfo.builder().group(group).storageId(storageId).build());
        //将文件数据响应给前端
        HttpHeaders httpHeaders = new HttpHeaders();
        String filename = "img" + DateTime.now().toString("yyyyMMddHHmmss") + "jpg";
        httpHeaders.setContentDispositionFormData("attachment",filename);
        httpHeaders.setContentType(MediaType.IMAGE_JPEG);
        return new ResponseEntity<>(bytes,httpHeaders, HttpStatus.CREATED);
    }

    @SneakyThrows
    @ApiOperation("删除文件")
    @DeleteMapping("remove")
    @ResponseBody
    public JsonVO<Integer> delete(String group,String storageId){
        int i = dfsClient.deleteFile(FastDfsFileInfo.builder().group(group).storageId(storageId).build());
        if (i == 0){
            return JsonVO.success(0);
        }
        return JsonVO.fail(i);
    }
}
